<template>
  <div class="product-image-container">
    <!-- 骨架屏 -->
    <van-skeleton title :row="0" :loading="loading">
      <template #template>
        <div class="skeleton-box"></div>
      </template>
    </van-skeleton>

    <!-- 图片 -->
    <img
      v-show="!loading"
      :src="imageUrl"
      :alt="alt"
      class="product-image"
      @load="handleImageLoaded"
      @error="handleImageError"
    />

    <!-- 加载失败显示的内容 -->
    <div v-if="loadError" class="error-placeholder">
      <van-icon name="photo-fail" />
      <span>加载失败</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { apiGetProductDetail } from '../api/product'

const props = defineProps({
  itemId: {
    type: String,
    required: true
  },
  alt: {
    type: String,
    default: '商品图片'
  }
})

const loading = ref(true)
const loadError = ref(false)
const imageUrl = ref('')

// 加载图片
const loadImage = async () => {
  try {
    loading.value = true
    loadError.value = false
    const res = await apiGetProductDetail(props.itemId)
    imageUrl.value = res.image
  } catch (err) {
    console.error('加载图片失败:', err)
    loadError.value = true
  }
}

// 图片加载完成
const handleImageLoaded = () => {
  loading.value = false
}

// 图片加载失败
const handleImageError = () => {
  loading.value = false
  loadError.value = true
}

onMounted(() => {
  loadImage()
})
</script>

<style scoped>
.product-image-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.skeleton-box {
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  border-radius: 4px;
}

.error-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #999;
  border-radius: 4px;
}

.error-placeholder .van-icon {
  font-size: 24px;
  margin-bottom: 8px;
}
</style> 